package org.jeecg.modules.middleware.quartz.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.ecloud.sdk.util.DateUtil;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.shiboetc.ShiBoEtcService;
import org.jeecg.modules.wlhy.shiboetc.ShiboEtcReport;
import org.jeecg.modules.wlhy.shiboetc.ShiboEtcReportDTO;
import org.jeecg.modules.wlhy.shiboetc.service.IHyShiboectReportService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.factory.annotation.Autowired;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class ShiboEtcUploadJobService implements Job {

    @Autowired
    private IHyShiboectReportService shiboectReportService;
    @Autowired
    private IHyVehicleService hyVehicleService;
    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ShiBoEtcService shiBoEtcService;


    @Override
    public void execute(org.quartz.JobExecutionContext context) {
        log.info("视博ETC上传数据开始");

        QueryWrapper<ShiboEtcReportDTO> queryWrapper = new QueryWrapper();
        //运单
        queryWrapper.eq("shipping.shipping_status", "5");
        queryWrapper.eq("shipping.tos_identification","0");
        queryWrapper.ne("sbect.upload_status","1").or().isNull("sbect.upload_status");
        queryWrapper.like("shipping.shipping_note_number","YD");
        queryWrapper.orderByDesc("shipping.pay_dt");
        IPage<ShiboEtcReportDTO> pageList;
        Page<ShiboEtcReportDTO> page = new Page<ShiboEtcReportDTO>(1, 10);
        pageList = shiboectReportService.getShiboEtcList1(page, queryWrapper);

        int num = 0;
        if (pageList.getRecords().size() > 0) {
            for (ShiboEtcReportDTO shiboEtcReportDTO : pageList.getRecords()) {
                log.info("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"开始上报");
                try {
                    HyVehicle vehicle = hyVehicleService.getById(shiboEtcReportDTO.getVehicleId());
                    HyDriver driver = hyDriverService.getDriverById(shiboEtcReportDTO.getDriverId());

                    String company3DESKey = null;
                    Boolean result = true;
                    boolean hasKey = redisUtil.hasKey("shibo3des");
                    if (hasKey==true){
                        company3DESKey = redisUtil.get("shibo3des").toString();
                    }

                    if (company3DESKey!=null){
                        //确认密钥是否可用
                        result = shiBoEtcService.doCompanyDesAck(company3DESKey);
                    }
                    if (company3DESKey==null||result==false){
                        //获取3ds密钥
                        company3DESKey = shiBoEtcService.getCompany3DESKey();
                    }
                    //上传车辆
                    Result<?> veResult = shiBoEtcService.vehicleFiling(vehicle,company3DESKey);
                    //如果失败则返回错误信息
                    String time = DateUtil.getTime();
                    if (!veResult.isSuccess()){
                        log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报车辆失败，失败原因为++"+veResult.getMessage());
                        updateShiboectReport(shiboEtcReportDTO, veResult);
                        continue;
                    }
                    //对运单的签收时间跟现在的时间进行比较，如果大于3天则上传历史运单
                    long day = DateUtil.getDaySub(DateUtil.getStringDate(shiboEtcReportDTO.getStatusDtLoading()),time);
                    if (day>=3){
                        Result<?> HistoryResult = shiBoEtcService.waybillHistoryStart(vehicle,shiboEtcReportDTO,company3DESKey);
                        updateShiboectReport(shiboEtcReportDTO,HistoryResult);
                        if (!HistoryResult.isSuccess()){
                            log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报历史运单失败，失败原因为++"+HistoryResult.getMessage());
                            continue;
                        }
                        num++;
                    }else {
                        //开始上传运单
                        Result<?> startResult = shiBoEtcService.waybillStart(shiboEtcReportDTO,vehicle,company3DESKey);
                        if (!startResult.isSuccess()){
                            updateShiboectReport(shiboEtcReportDTO,startResult);
                            log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报运单失败，失败原因为++"+startResult.getMessage());
                            continue;
                        }
                        //上传原始运单
                        Result<?> result2 = shiBoEtcService.originWaybillEnd(shiboEtcReportDTO,vehicle,driver,company3DESKey);
                        if (!result2.isSuccess()){
                            updateShiboectReport(shiboEtcReportDTO,result2);
                            log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报原始运单失败，失败原因为++"+result2.getMessage());
                            continue;
                        }
                        //上传结束运单
                        Result<?> endResult= shiBoEtcService.waybillEnd(shiboEtcReportDTO,company3DESKey);
                        if (!endResult.isSuccess()){
                            updateShiboectReport(shiboEtcReportDTO,endResult);
                            log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报结束运单失败，失败原因为++"+endResult.getMessage());
                            continue;
                        }

                        if (startResult.isSuccess()&&result2.isSuccess()&&endResult.isSuccess()){
                            num++;
                            updateShiboectReport(shiboEtcReportDTO,endResult);
                        }
                    }
                } catch (Exception e) {
                    log.error("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报失败，失败原因为++"+e.getMessage());
                }
                log.info("运单号为"+shiboEtcReportDTO.getShippingNoteNumber()+"上报结束");
            }
        }
        log.info("视博ETC上传数据结束,上传成功"+num+"条");
    }
    private void updateShiboectReport(HyShippingNote shippingNote, Result<?> result){
        String time = DateUtil.getTime();
        ShiboEtcReport shiboEtcReport = new ShiboEtcReport();
        shiboEtcReport.setShippingId(shippingNote.getId());
        shiboEtcReport.setShippingNoteNumber(shippingNote.getShippingNoteNumber());
        if (result.isSuccess()){
            shiboEtcReport.setUploadStatus("1");
        }else {
            shiboEtcReport.setUploadStatus("2");
        }
        shiboEtcReport.setUploadDate(DateUtil.fomatDate(time));
        shiboEtcReport.setCreateBy(UserUtil.getLoginUser().getUsername());
        shiboEtcReport.setFailureReason(result.getMessage());
        Integer count = shiboectReportService.getCount(shippingNote.getId());
        if (count==0){
            shiboectReportService.save(shiboEtcReport);
        }else {
            ShiboEtcReport info = shiboectReportService.getInfoByShippingId(shippingNote.getId());
            shiboEtcReport.setId(info.getId());
            shiboectReportService.updateById(shiboEtcReport);
        }

    }
}
